#!/usr/bin/python


import gobject
import gtk, gtkmozembed
import os
import re
import time
import sys
import urllib,urlparse
from threading import Thread
import threading
import traceback








class MVFileChecker(Thread):
	CURRENT_TEMPLATE_FILE =None
	SONG_FILE='~/.quodlibet/current'
	TEMPLATES_DIR='templates'
	LAST_SONG_DATE=None
	LAST_TEMPLATE_DATE=None
	alive=True
	autoload=True
	currentTemplate=0
	moz=gtkmozembed.MozEmbed()
	semaphore=threading.Semaphore()
	operation=False
	

	def loadHtml(self):
		path=self.getTemplatePath()
		data=self.getData()
		try:
			self.semaphore.acquire()
			print "aquiring semaphore"
			uri='file://' + urllib.pathname2url(os.path.abspath(path))
			self.moz.render_data(data,len(data),uri,'text/html')
			print "releasing semaphore"
			self.semaphore.release()
		except:
			semaphore.release()
			traceback.print_exc()
			
	def initTemplates(self):
		dir_content=os.listdir(self.TEMPLATES_DIR)
		self.templateList=[]
		for t in dir_content:
			if t[0]!= "." and t[0]!="_":
				self.templateList.append(t)
		self.templateList.sort()
		print "templates are: ", self.templateList
		

	def stop(self):
		self.alive=False
	
	def switchAutoload(self):
		if self.autoload:
			print "Autoload: off"
			self.autoload=False
		else:
			print "Autoload: on"
			self.autoload=True
	
	def switchTemplate(self):
		self.currentTemplate=((self.currentTemplate+1)%len(self.templateList))
		self.CURRENT_TEMPLATE_FILE=self.templateList[self.currentTemplate]
		self.LAST_TEMPLATE_DATE=0
		#loadHtml()
		
	def setHomeTemplate(self):
		self.currentTemplate=0
		self.CURRENT_TEMPLATE_FILE=self.templateList[0]
		self.LAST_SONG_DATE=0
		#loadHtml()
		

	def getAttributeByPattern(self,data,string):
		try:
			#return ""
			el= re.compile("^"+string+".*$", re.M).search(data).group()
			#el=cgi.escape(el)
			#el=urllib2.
		except:
			print "Errore: '%s' non trovato" % string
			el=""
		return el.replace(string,"")
			
	def getSongFileContent(self):
		f=open(os.path.expanduser(self.SONG_FILE), 'r')
		data = f.read()
		f.close()
		return data
	
	def getTemplatePath(self):
		return os.path.expanduser("%s/%s/index.html"%(self.TEMPLATES_DIR,self.CURRENT_TEMPLATE_FILE))
	
	def getTemplateFileContent(self):
		f=open(self.getTemplatePath(), 'r')
		data = f.read()
		f.close()
		return data

	def getCoverPath(self,data):
		clist=["cover.jpg","folder.jpg",".folder.jpg"]
		base=os.path.split(self.getAttributeByPattern(data,"~filename="))[0]
		for c in clist:
			if os.path.isfile(base+"/"+c):
				return base+"/"+c
			else:
				return os.path.abspath("./%s/%s/cover.png"%(self.TEMPLATES_DIR,self.CURRENT_TEMPLATE_FILE))
	
	def getData(self):
		try:
			data = self.getTemplateFileContent()
			song_data =self.getSongFileContent()
			
			data=data.replace("%raw_data%",song_data)
			data=data.replace("%album%",self.getAttributeByPattern(song_data,"album="))
			data=data.replace("%artist%",self.getAttributeByPattern(song_data,"artist="))
			data=data.replace("%cover%","file://"+urllib.pathname2url(self.getCoverPath(song_data)))
			data=data.replace("%title%",self.getAttributeByPattern(song_data,"title="))
			data=data.replace("%composer%",self.getAttributeByPattern(song_data,"composer="))
			
			return data
		except:
			print "Errore nella generazione del codice HTML"
			return "<h1>ERROR: template or song file not found: probably quodlibet not started</h1>"
			
		

	
	def run(self):
		while gtk.events_pending():
			gtk.main_iteration()
		while self.alive:
			time.sleep(1.0)
			if self.autoload:
				#print "Checking file change"
				try:
					template_stats=os.stat(self.getTemplatePath())
					song_stats=os.stat(os.path.expanduser(self.SONG_FILE))
					if(time.localtime(song_stats[8])>self.LAST_SONG_DATE):
						print "Song variation found"
						self.LAST_SONG_DATE=time.localtime(song_stats[8])
						self.operation=True
						
				except:
					print "Error in update thread", traceback.print_exc()
			
	
	def main_loop(self):
		while self.alive:
			if self.operation:
				self.loadHtml()
				self.operation=False
			while gtk.events_pending():
				gtk.main_iteration()
			time.sleep(0.01)	


	def keyPressed(self,win,event):
		if event.string=="f":
			if self.fullscreen:
				win.unfullscreen()
				self.fullscreen=False
			else:
				win.fullscreen();
				self.fullscreen=True
		
		if event.string.lower()=="c":
			self.switchTemplate()
			self.loadHtml()
		elif event.string.lower()=="q":
			self.quit()
		elif event.string.lower()=="r":
			self.loadHtml()
		elif event.string.lower()=="a":
			self.self.switchAutoload()
		elif event.string.lower()=="h":
			self.setHomeTemplate()
			self.loadHtml()
		elif self.commands.has_key(event.string.lower()):
			self.execute(self.commands[event.string.lower()])
		else:
			print "No key-binding for '%s'"&event.string.lower()
			
	def quit(self,widget=None,event=None):
		print "Procedura di chiusura"
		self.stop()
		gtk.main_quit()
		
	
	def __init__ (self):
		Thread.__init__(self)
		self.initTemplates()
		self.CURRENT_TEMPLATE_FILE=self.templateList[0]
		self.initGui()
		self.initKeyBinding()
		
	def initKeyBinding(self):
		self.commands={}
		self.commands[' ']="quodlibet --play-pause"
		self.commands['n']="quodlibet --next"
		self.commands['p']="quodlibet --previous"
		
	
	def execute(self,cmd):
		try:
			os.system(cmd)
		except:
			print "error with command execution"
		
	def initGui(self):
		self.fullscreen=False
		self.semaphore=threading.Semaphore()
		self.win = gtk.Window()
		self.win.add(self.moz)
		
		self.win.connect("delete-event", self.quit)
		self.win.connect("key-press-event",self.keyPressed)
		self.win.set_border_width(0)
		self.win.set_title("Music Viewer")
		self.win.set_default_size(900,500)
		self.win.show_all()
		self.loadHtml()
	
if __name__ == '__main__':
	gobject.threads_init() #rende non  bloccante il main
	mv=MVFileChecker()
	mv.start()
	mv.main_loop()
	#gtk.main()
	


